import React, { useEffect, useState } from 'react'
import {Table, Tag, Button, Modal, Popover, Switch } from "antd"
import  axios  from 'axios';
import { 
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined } 
from '@ant-design/icons';
const { confirm } = Modal;

export default function RightList() {
  const [dataSource, setdataSource] = useState([])

  useEffect(() => {
    axios.get("/rights?_embed=children").then(res => {
    const list = res.data
    list.forEach(item => {
      if(item.children.length === 0) {
        item.children = ""
      }
    })
    setdataSource(res.data)
    })
  }, [])

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (key) => {
        return <Tag color="cyan">{key}</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button danger type="primary" shape="circle" icon={<DeleteOutlined />} 
          onClick={() => confirmMethod(item)}
          />
          <Popover content={<div style={{textAlign: "center"}}>
            <Switch checked={item.pagepermisson} onChange={()=>switchMethod(item)}></Switch>
          </div>} title="页面配置项" trigger={item.pagepermisson===undefined?"":"click"}>
            <Button disabled={item.pagepermisson===undefined} type="primary" shape="circle" icon={<EditOutlined />} />
          </Popover>
        </div>
      }
    },
  ];
  // 开关的显示与隐藏
  const switchMethod = (item) => {
    item.pagepermisson = item.pagepermisson===1?0:1
    // console.log(item);
    setdataSource([...dataSource])
    if(item.grade===1) {
      axios.patch(`/rights/${item.id}`, {
        pagepermisson: item.pagepermisson
      })
    }else {
      axios.patch(`/children/${item.id}`, {
        pagepermisson: item.pagepermisson
      })
    }
  }

  // 确定是否删除提示框
  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }
  // 删除处理逻辑
  const deleteMethod = (item) => {
    console.log(item);
    // 当前页面同步状态 + 后端同步
    if(item.grade===1) {
      setdataSource(dataSource.filter(data=>data.id !== item.id))
      axios.delete(`/rights/${item.id}`)
    }else {
      // console.log(item.rightId);
      let list = dataSource.filter(data=>data.id === item.rightId)
      // console.log(list);
      list[0].children = list[0].children.filter(data=>data.id!==item.id)
      setdataSource([...dataSource])
      axios.delete(`/children/${item.id}`)
    }
  }

  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
      pagination={{
        pageSize: 5
      }}
      />
    </div>
  )
}
